import React, { createContext, useContext, useEffect, useState } from 'react';
import { useAccountStore } from '../stores/accountStore';
import { Account } from '../stores/accountStore';

interface AccountContextType {
  currentAccount: Account | null;
  switchAccount: (accountId: string) => Promise<void>;
  refreshCurrentAccount: () => Promise<void>;
}

const AccountContext = createContext<AccountContextType | undefined>(undefined);

export const useAccountContext = () => {
  const context = useContext(AccountContext);
  if (context === undefined) {
    throw new Error('useAccountContext must be used within an AccountProvider');
  }
  return context;
};

interface AccountProviderProps {
  children: React.ReactNode;
}

export const AccountProvider: React.FC<AccountProviderProps> = ({ children }) => {
  const { 
    currentAccount, 
    switchCurrentAccount, 
    fetchAccounts 
  } = useAccountStore();
  
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    const initializeAccount = async () => {
      try {
        await fetchAccounts();
        setIsInitialized(true);
      } catch (error) {
        console.error('初始化账号失败:', error);
        setIsInitialized(true);
      }
    };

    initializeAccount();
  }, [fetchAccounts]);

  const switchAccount = async (accountId: string) => {
    try {
      await switchCurrentAccount(accountId);
      await refreshCurrentAccount();
    } catch (error) {
      console.error('切换账号失败:', error);
      throw error;
    }
  };

  const refreshCurrentAccount = async () => {
    try {
      await fetchAccounts();
    } catch (error) {
      console.error('刷新当前账号失败:', error);
    }
  };

  const value: AccountContextType = {
    currentAccount,
    switchAccount,
    refreshCurrentAccount,
  };

  if (!isInitialized) {
    return <div>加载中...</div>;
  }

  return (
    <AccountContext.Provider value={value}>
      {children}
    </AccountContext.Provider>
  );
}; 